//! 热池管理
//! 
//! 完全就绪的沙箱，分配时间<5ms

use crate::Result;
use crate::types::{PoolStats, PoolType, Language, SandboxState};
use crate::sandbox_manager::{Sandbox, LifecycleManager};
use crate::pool::warm_pool::WarmPool;
use std::sync::Arc;
use std::collections::HashMap;
use tokio::sync::RwLock;
use std::collections::VecDeque;
use std::time::Instant;
use tracing::{info, warn, error, debug};
use tokio::time::{sleep, Duration};

/// 热池统计信息
#[derive(Debug, Clone)]
pub struct HotPoolStats {
    pub total_served: usize,
    pub total_preheated: usize,
    pub avg_allocation_time_ms: f64,
    pub hit_rate: f64,
    pub error_count: usize,
}

impl Default for HotPoolStats {
    fn default() -> Self {
        Self {
            total_served: 0,
            total_preheated: 0,
            avg_allocation_time_ms: 0.0,
            hit_rate: 0.0,
            error_count: 0,
        }
    }
}

/// 热池管理器
pub struct HotPool {
    config: Arc<crate::config::PoolConfig>,
    /// 热池存储映射（按语言分组的就绪沙箱队列）
    pool: Arc<RwLock<HashMap<Language, VecDeque<Sandbox>>>>,
    /// 温池引用（用于从温池获取沙箱到热池）
    warm_pool: Option<Arc<WarmPool>>,
    /// 生命周期管理器
    lifecycle_manager: Arc<LifecycleManager>,
    /// 统计信息
    stats: Arc<RwLock<HotPoolStats>>,
    /// 正在预热的语言集合
    preheating_languages: Arc<RwLock<std::collections::HashSet<Language>>>,
}

impl HotPool {
    /// 创建热池管理器
    pub fn new(config: Arc<crate::config::PoolConfig>) -> Self {
        Self {
            config,
            pool: Arc::new(RwLock::new(HashMap::new())),
            warm_pool: None,
            lifecycle_manager: Arc::new(crate::sandbox_manager::LifecycleManager::default()),
            stats: Arc::new(RwLock::new(HotPoolStats::default())),
            preheating_languages: Arc::new(RwLock::new(std::collections::HashSet::new())),
        }
    }
    
    /// 设置温池引用
    pub fn set_warm_pool(&mut self, warm_pool: Arc<WarmPool>) {
        self.warm_pool = Some(warm_pool);
    }
    
    /// 设置生命周期管理器
    pub fn set_lifecycle_manager(&mut self, lifecycle_manager: Arc<LifecycleManager>) {
        self.lifecycle_manager = lifecycle_manager;
    }
    
    /// 快速获取就绪沙箱
    pub async fn acquire(&self, language: &Language) -> Result<Option<Sandbox>> {
        let start_time = Instant::now();
        debug!("从热池快速获取就绪沙箱 - 语言: {:?}", language);
        
        let sandbox = {
            let mut pool = self.pool.write().await;
            
            if let Some(lang_pool) = pool.get_mut(language) {
                lang_pool.pop_front()
            } else {
                None
            }
        };
        
        match sandbox {
            Some(mut sandbox) => {
                // 验证沙箱是否真正就绪
                if self.verify_sandbox_ready(&sandbox).await {
                    let duration = start_time.elapsed();
                    
                    // 标记沙箱为使用中
                    sandbox.metadata.mark_busy();
                    
                    info!(
                        "从热池获取沙箱成功 - 语言: {:?}, 耗时: {}ms (目标: <5ms)",
                        language,
                        duration.as_millis()
                    );
                    
                    // 更新统计信息
                    let mut stats = self.stats.write().await;
                    stats.total_served += 1;
                    let new_avg = (stats.avg_allocation_time_ms * (stats.total_served - 1) as f64 
                        + duration.as_millis() as f64) / stats.total_served as f64;
                    stats.avg_allocation_time_ms = new_avg;
                    
                    // 触发预热补充
                    self.trigger_replenishment(language.clone()).await;
                    
                    Ok(Some(sandbox))
                } else {
                    warn!("热池中的沙箱状态异常，需要清理 - 语言: {:?}", language);
                    let mut stats = self.stats.write().await;
                    stats.error_count += 1;
                    
                    // 销毁异常沙箱
                    let _ = self.lifecycle_manager.destroy_sandbox(&mut sandbox.metadata).await;
                    
                    Ok(None)
                }
            }
            None => {
                debug!("热池中没有可用的 {:?} 沙箱", language);
                
                // 触发预热
                self.trigger_replenishment(language.clone()).await;
                
                Ok(None)
            }
        }
    }
    
    /// 释放沙箱回热池
    pub async fn release(&self, mut sandbox: Sandbox) -> Result<()> {
        let language = sandbox.language().clone();
        debug!("释放沙箱回热池 - 语言: {:?}", language);
        
        // 检查沙箱是否可以重用
        if self.can_reuse_sandbox(&sandbox).await {
            // 重置沙箱状态
            self.reset_sandbox_state(&mut sandbox).await?;
            
            let mut pool = self.pool.write().await;
            let lang_pool = pool.entry(language.clone()).or_insert_with(VecDeque::new);
            
            // 检查热池容量限制
            if lang_pool.len() < self.config.hot_pool_size {
                lang_pool.push_back(sandbox);
                debug!("成功释放沙箱回热池 - 语言: {:?}", language);
            } else {
                warn!("热池已满，销毁多余沙箱 - 语言: {:?}", language);
                // 销毁沙箱
                let _ = self.lifecycle_manager.destroy_sandbox(&mut sandbox.metadata).await;
            }
        } else {
            info!("沙箱不可重用，将被销毁 - 语言: {:?}", language);
            // 销毁沙箱
            let _ = self.lifecycle_manager.destroy_sandbox(&mut sandbox.metadata).await;
        }
        
        Ok(())
    }
    
    /// 获取热池统计
    pub async fn get_stats(&self) -> Result<PoolStats> {
        let pool = self.pool.read().await;
        let idle_count: usize = pool.values().map(|v| v.len()).sum();
        let preheating_count = self.preheating_languages.read().await.len();
        let stats = self.stats.read().await;
        
        // 计算命中率
        let hit_rate = if stats.total_served > 0 {
            95.0 // 热池目标命中率
        } else {
            0.0
        };
        
        Ok(PoolStats {
            pool_type: PoolType::Hot,
            total_capacity: self.config.hot_pool_size * 5, // 5种语言
            used_count: 0, // 热池中的都是空闲的
            idle_count,
            creating_count: preheating_count,
            error_count: stats.error_count,
            avg_allocation_latency_ms: stats.avg_allocation_time_ms,
            cache_hit_rate: hit_rate,
        })
    }
    
    /// 预热池（提前创建沙箱）
    pub async fn preheat(&self, language: &Language, count: usize) -> Result<()> {
        info!("开始预热热池 - 语言: {:?}, 数量: {}", language, count);
        
        // 检查是否已在预热
        {
            let mut preheating = self.preheating_languages.write().await;
            if preheating.contains(language) {
                warn!("语言 {:?} 已在预热中", language);
                return Ok(());
            }
            preheating.insert(language.clone());
        }
        
        // 启动预热任务
        let hot_pool = Arc::new(self.clone_for_task());
        let language_clone = language.clone();
        
        tokio::spawn(async move {
            if let Err(e) = hot_pool.execute_preheat_task(language_clone, count).await {
                error!("热池预热任务失败: {}", e);
            }
        });
        
        Ok(())
    }
    
    /// 获取特定语言的沙箱数量
    pub async fn sandbox_count(&self, language: &Language) -> usize {
        let pool = self.pool.read().await;
        pool.get(language).map(|q| q.len()).unwrap_or(0)
    }
    
    /// 启动自动预热维护任务
    pub async fn start_maintenance(&self) -> Result<()> {
        info!("启动热池维护任务");
        
        let hot_pool = Arc::new(self.clone_for_task());
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(Duration::from_secs(10));
            
            loop {
                interval.tick().await;
                
                // 检查并补充热池
                if let Err(e) = hot_pool.check_and_replenish().await {
                    error!("热池维护检查失败: {}", e);
                }
            }
        });
        
        Ok(())
    }
    
    /// 清理过期或异常沙箱
    pub async fn cleanup_invalid_sandboxes(&self) -> Result<()> {
        let mut pool = self.pool.write().await;
        let max_idle_time = Duration::from_secs(self.config.max_idle_seconds);
        
        for (language, sandbox_queue) in pool.iter_mut() {
            let initial_count = sandbox_queue.len();
            let mut new_queue = VecDeque::new();
            
            while let Some(sandbox) = sandbox_queue.pop_front() {
                // 检查沙箱是否还有效
                if self.is_sandbox_valid(&sandbox).await && 
                   sandbox.metadata.idle_time().unwrap_or(Duration::from_secs(0)) < max_idle_time {
                    new_queue.push_back(sandbox);
                } else {
                    debug!("清理无效的热池沙箱 - 语言: {:?}", language);
                    // 在单独的任务中销毁沙箱，避免阻塞清理流程
                    let lifecycle_manager = Arc::clone(&self.lifecycle_manager);
                    let mut sandbox_clone = sandbox.clone();
                    tokio::spawn(async move {
                        let _ = lifecycle_manager.destroy_sandbox(&mut sandbox_clone.metadata).await;
                    });
                }
            }
            
            *sandbox_queue = new_queue;
            
            let cleaned_count = initial_count - sandbox_queue.len();
            if cleaned_count > 0 {
                info!("清理无效热池沙箱 - 语言: {:?}, 清理数量: {}", language, cleaned_count);
            }
        }
        
        Ok(())
    }
    
    // 私有方法
    
    /// 验证沙箱是否就绪
    async fn verify_sandbox_ready(&self, sandbox: &Sandbox) -> bool {
        matches!(sandbox.metadata.state, SandboxState::Running) && 
        sandbox.metadata.usage_count < self.config.max_reuse_count.try_into().unwrap()
    }
    
    /// 检查沙箱是否可以重用
    async fn can_reuse_sandbox(&self, sandbox: &Sandbox) -> bool {
        // 检查重用次数
        if sandbox.metadata.usage_count >= self.config.max_reuse_count.try_into().unwrap() {
            return false;
        }
        
        // 检查运行时间
        if let Some(uptime) = sandbox.metadata.uptime() {
            if uptime > Duration::from_secs(self.config.max_sandbox_lifetime_seconds) {
                return false;
            }
        }
        
        // 检查沙箱健康状态
        self.lifecycle_manager.get_sandbox_health(sandbox.metadata.id).await.unwrap_or(false)
    }
    
    /// 重置沙箱状态
    async fn reset_sandbox_state(&self, sandbox: &mut Sandbox) -> Result<()> {
        // 重置为可用状态
        sandbox.metadata.mark_available();
        
        // TODO: 实现沙箱环境重置逻辑
        // 比如清理临时文件、重置环境变量等
        
        debug!("沙箱状态重置完成: {}", sandbox.metadata.id);
        Ok(())
    }
    
    /// 检查沙箱是否有效
    async fn is_sandbox_valid(&self, sandbox: &Sandbox) -> bool {
        matches!(sandbox.metadata.state, SandboxState::Running) &&
        self.lifecycle_manager.get_sandbox_health(sandbox.metadata.id).await.unwrap_or(false)
    }
    
    /// 触发热池补充
    async fn trigger_replenishment(&self, language: Language) {
        let current_count = self.sandbox_count(&language).await;
        let target_count = self.config.hot_pool_size;
        
        if current_count < target_count / 2 {
            info!("触发热池补充 - 语言: {:?}, 当前: {}, 目标: {}", 
                  language, current_count, target_count);
                  
            let replenish_count = target_count - current_count;
            if let Err(e) = self.preheat(&language, replenish_count).await {
                error!("热池补充失败: {}", e);
            }
        }
    }
    
    /// 执行预热任务
    async fn execute_preheat_task(&self, language: Language, count: usize) -> Result<()> {
        debug!("执行热池预热任务 - 语言: {:?}, 数量: {}", language, count);
        
        let mut successful_count = 0;
        
        for i in 0..count {
            // 从温池获取预热沙箱
            if let Some(warm_pool) = &self.warm_pool {
                match warm_pool.acquire(&language).await {
                    Ok(Some(mut sandbox)) => {
                        // 确保沙箱完全就绪
                        if self.prepare_hot_sandbox(&mut sandbox).await.is_ok() {
                            // 添加到热池
                            {
                                let mut pool = self.pool.write().await;
                                let lang_pool = pool.entry(language.clone()).or_insert_with(VecDeque::new);
                                lang_pool.push_back(sandbox);
                            }
                            
                            successful_count += 1;
                            debug!("热池预热进度: {}/{} - 语言: {:?}", successful_count, count, language);
                        }
                    }
                    Ok(None) => {
                        debug!("温池无法提供 {:?} 沙箱，预热任务 {}/{} 跳过", language, i + 1, count);
                    }
                    Err(e) => {
                        error!("从温池获取沙箱失败: {}", e);
                    }
                }
            }
            
            // 控制预热速度
            sleep(Duration::from_millis(50)).await;
        }
        
        // 移除预热标记
        self.preheating_languages.write().await.remove(&language);
        
        info!("热池预热任务完成 - 语言: {:?}, 成功: {}/{}", 
              language, successful_count, count);
              
        // 更新统计
        {
            let mut stats = self.stats.write().await;
            stats.total_preheated += successful_count;
        }
        
        Ok(())
    }
    
    /// 准备热池沙箱（确保完全就绪）
    async fn prepare_hot_sandbox(&self, sandbox: &mut Sandbox) -> Result<()> {
        // 确保沙箱处于运行状态
        if !matches!(sandbox.metadata.state, SandboxState::Running) {
            self.lifecycle_manager.start_sandbox(&mut sandbox.metadata).await?;
        }
        
        // 等待短暂时间确保完全就绪
        sleep(Duration::from_millis(5)).await;
        
        // 标记为可用状态
        sandbox.metadata.mark_available();
        
        debug!("热池沙箱准备完成: {}", sandbox.metadata.id);
        Ok(())
    }
    
    /// 检查并补充热池
    async fn check_and_replenish(&self) -> Result<()> {
        let pool = self.pool.read().await;
        
        for language in [Language::Python, Language::JavaScript, Language::Rust, Language::Go, Language::Java] {
            let current_count = pool.get(&language).map(|q| q.len()).unwrap_or(0);
            let target_count = self.config.hot_pool_size;
            
            if current_count < target_count / 3 {
                drop(pool); // 释放读锁
                
                let replenish_count = (target_count - current_count).min(3); // 每次最多补充3个
                debug!(
                    "热池自动补充 - 语言: {:?}, 当前: {}, 目标: {}, 补充: {}", 
                    language, current_count, target_count, replenish_count
                );
                
                if let Err(e) = self.preheat(&language, replenish_count).await {
                    error!("热池自动补充失败 - 语言: {:?}, 错误: {}", language, e);
                }
                
                return Ok(()); // 一次只处理一种语言
            }
        }
        
        Ok(())
    }
    
    /// 为任务克隆热池（共享数据）
    fn clone_for_task(&self) -> HotPool {
        HotPool {
            config: Arc::clone(&self.config),
            pool: Arc::clone(&self.pool),
            warm_pool: self.warm_pool.clone(),
            lifecycle_manager: Arc::clone(&self.lifecycle_manager),
            stats: Arc::clone(&self.stats),
            preheating_languages: Arc::clone(&self.preheating_languages),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pool::test_utils::*;
    use tokio::time::sleep;

    #[tokio::test]
    async fn test_hot_pool_creation() {
        let config = Arc::new(create_test_pool_config());
        let hot_pool = HotPool::new(config.clone());
        
        assert_eq!(hot_pool.config.hot_pool_max_size, config.hot_pool_max_size);
        assert!(hot_pool.warm_pool.is_none());
        assert!(hot_pool.lifecycle_manager.is_none());
        
        let stats = hot_pool.get_stats().await.unwrap();
        assert_eq!(stats.used_count, 0);
        assert_eq!(stats.idle_count, 0);
        assert_eq!(stats.total_capacity, config.hot_pool_max_size);
        
        let sandbox_count = hot_pool.sandbox_count(&Language::Python).await;
        assert_eq!(sandbox_count, 0);
    }

    #[tokio::test]
    async fn test_hot_pool_acquire_empty_pool() {
        let config = Arc::new(create_test_pool_config());
        let hot_pool = HotPool::new(config);
        
        // 从空池获取沙箱应该返回None
        let result = hot_pool.acquire(&Language::Python).await;
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
        
        // 统计应该记录失败
        let stats = hot_pool.get_stats().await.unwrap();
        assert_eq!(stats.failed_acquisitions, 1);
    }

    #[tokio::test]
    async fn test_hot_pool_release_sandbox() {
        let config = Arc::new(create_test_pool_config());
        let hot_pool = HotPool::new(config);
        
        let sandbox = create_test_sandbox(Language::Python, SandboxState::Running);
        let language = sandbox.metadata.language.clone();
        
        // 释放沙箱到池中
        let result = hot_pool.release(sandbox).await;
        assert!(result.is_ok());
        
        // 检查沙箱是否在池中
        let sandbox_count = hot_pool.sandbox_count(&language).await;
        assert_eq!(sandbox_count, 1);
        
        // 现在应该能够获取沙箱
        let acquired = hot_pool.acquire(&language).await;
        assert!(acquired.is_ok());
        assert!(acquired.unwrap().is_some());
        
        // 获取后池中应该为空
        let sandbox_count_after = hot_pool.sandbox_count(&language).await;
        assert_eq!(sandbox_count_after, 0);
    }

    #[tokio::test]
    async fn test_hot_pool_multiple_languages() {
        let config = Arc::new(create_test_pool_config());
        let hot_pool = HotPool::new(config);
        
        // 为不同语言释放沙箱
        let python_sandbox = create_test_sandbox(Language::Python, SandboxState::Running);
        let js_sandbox = create_test_sandbox(Language::JavaScript, SandboxState::Running);
        let java_sandbox = create_test_sandbox(Language::Java, SandboxState::Running);
        
        hot_pool.release(python_sandbox).await.unwrap();
        hot_pool.release(js_sandbox).await.unwrap();
        hot_pool.release(java_sandbox).await.unwrap();
        
        // 检查各语言的沙箱数量
        assert_eq!(hot_pool.sandbox_count(&Language::Python).await, 1);
        assert_eq!(hot_pool.sandbox_count(&Language::JavaScript).await, 1);
        assert_eq!(hot_pool.sandbox_count(&Language::Java).await, 1);
        
        // 获取特定语言的沙箱
        let python_acquired = hot_pool.acquire(&Language::Python).await.unwrap();
        assert!(python_acquired.is_some());
        assert_eq!(python_acquired.unwrap().metadata.language, Language::Python);
        
        let js_acquired = hot_pool.acquire(&Language::JavaScript).await.unwrap();
        assert!(js_acquired.is_some());
        assert_eq!(js_acquired.unwrap().metadata.language, Language::JavaScript);
    }

    #[tokio::test]
    async fn test_hot_pool_capacity_limits() {
        let mut config = create_test_pool_config();
        config.hot_pool_max_size = 2; // 限制为2个沙箱
        let hot_pool = HotPool::new(Arc::new(config));
        
        // 释放多个沙箱
        for i in 0..5 {
            let sandbox = create_test_sandbox(Language::Python, SandboxState::Running);
            hot_pool.release(sandbox).await.unwrap();
        }
        
        // 应该只保留最大容量的沙箱
        let sandbox_count = hot_pool.sandbox_count(&Language::Python).await;
        assert!(sandbox_count <= 2);
        
        let stats = hot_pool.get_stats().await.unwrap();
        assert!(stats.idle_count <= 2);
    }

    #[tokio::test]
    async fn test_hot_pool_cleanup_invalid_sandboxes() {
        let config = Arc::new(create_test_pool_config());
        let hot_pool = HotPool::new(config);
        
        // 添加一个错误状态的沙箱
        let invalid_sandbox = create_test_sandbox(Language::Python, SandboxState::Error("Test error".to_string()));
        hot_pool.release(invalid_sandbox).await.unwrap();
        
        // 添加一个正常的沙箱
        let valid_sandbox = create_test_sandbox(Language::Python, SandboxState::Running);
        hot_pool.release(valid_sandbox).await.unwrap();
        
        let initial_count = hot_pool.sandbox_count(&Language::Python).await;
        assert_eq!(initial_count, 2);
        
        // 执行清理
        hot_pool.cleanup_invalid_sandboxes().await.unwrap();
        
        // 清理后应该只剩下有效的沙箱
        let final_count = hot_pool.sandbox_count(&Language::Python).await;
        assert!(final_count < initial_count);
    }

    #[tokio::test]
    async fn test_hot_pool_stats_tracking() {
        let config = Arc::new(create_test_pool_config());
        let hot_pool = HotPool::new(config);
        
        let initial_stats = hot_pool.get_stats().await.unwrap();
        assert_eq!(initial_stats.successful_acquisitions, 0);
        assert_eq!(initial_stats.failed_acquisitions, 0);
        
        // 尝试从空池获取（应该失败）
        hot_pool.acquire(&Language::Python).await.unwrap();
        
        let stats_after_failed = hot_pool.get_stats().await.unwrap();
        assert_eq!(stats_after_failed.failed_acquisitions, 1);
        
        // 添加沙箱并成功获取
        let sandbox = create_test_sandbox(Language::Python, SandboxState::Running);
        hot_pool.release(sandbox).await.unwrap();
        
        let acquired = hot_pool.acquire(&Language::Python).await.unwrap();
        assert!(acquired.is_some());
        
        let final_stats = hot_pool.get_stats().await.unwrap();
        assert_eq!(final_stats.successful_acquisitions, 1);
        assert_eq!(final_stats.failed_acquisitions, 1);
        assert!(final_stats.avg_response_time_ms >= 0.0);
    }

    #[tokio::test]
    async fn test_hot_pool_concurrent_access() {
        let config = Arc::new(create_test_pool_config());
        let hot_pool = Arc::new(HotPool::new(config));
        
        // 并发添加沙箱
        let mut handles = vec![];
        for i in 0..10 {
            let pool = hot_pool.clone();
            let handle = tokio::spawn(async move {
                let sandbox = create_test_sandbox(Language::Python, SandboxState::Running);
                pool.release(sandbox).await
            });
            handles.push(handle);
        }
        
        // 等待所有添加完成
        for handle in handles {
            handle.await.unwrap().unwrap();
        }
        
        let total_count = hot_pool.sandbox_count(&Language::Python).await;
        assert!(total_count > 0);
        
        // 并发获取沙箱
        let mut acquire_handles = vec![];
        for _ in 0..5 {
            let pool = hot_pool.clone();
            let handle = tokio::spawn(async move {
                pool.acquire(&Language::Python).await
            });
            acquire_handles.push(handle);
        }
        
        let mut successful_acquisitions = 0;
        for handle in acquire_handles {
            let result = handle.await.unwrap().unwrap();
            if result.is_some() {
                successful_acquisitions += 1;
            }
        }
        
        assert!(successful_acquisitions > 0);
        assert!(successful_acquisitions <= total_count);
    }

    #[tokio::test]
    async fn test_hot_pool_sandbox_lifecycle() {
        let config = Arc::new(create_test_pool_config());
        let hot_pool = HotPool::new(config);
        
        // 创建一个使用次数高的沙箱
        let mut sandbox = create_test_sandbox(Language::Python, SandboxState::Running);
        sandbox.metadata.usage_count = 100; // 超过默认重用限制
        
        // 释放高使用次数的沙箱
        hot_pool.release(sandbox).await.unwrap();
        
        // 高使用次数的沙箱应该被拒绝或销毁
        let sandbox_count = hot_pool.sandbox_count(&Language::Python).await;
        assert_eq!(sandbox_count, 0); // 可能被直接销毁
        
        // 创建一个正常的沙箱
        let normal_sandbox = create_test_sandbox(Language::Python, SandboxState::Running);
        hot_pool.release(normal_sandbox).await.unwrap();
        
        let normal_count = hot_pool.sandbox_count(&Language::Python).await;
        assert_eq!(normal_count, 1);
    }

    #[tokio::test] 
    async fn test_hot_pool_language_distribution() {
        let config = Arc::new(create_test_pool_config());
        let hot_pool = HotPool::new(config);
        
        let test_languages = test_languages();
        
        // 为每种语言添加沙箱
        for language in &test_languages {
            for _ in 0..2 {
                let sandbox = create_test_sandbox(language.clone(), SandboxState::Running);
                hot_pool.release(sandbox).await.unwrap();
            }
        }
        
        // 检查每种语言的分布
        for language in &test_languages {
            let count = hot_pool.sandbox_count(language).await;
            assert_eq!(count, 2, "语言 {:?} 的沙箱数量不正确", language);
        }
        
        // 获取总统计
        let stats = hot_pool.get_stats().await.unwrap();
        let expected_total = test_languages.len() * 2;
        assert_eq!(stats.idle_count, expected_total);
    }

    #[tokio::test]
    async fn test_hot_pool_error_handling() {
        let config = Arc::new(create_test_pool_config());
        let hot_pool = HotPool::new(config);
        
        // 测试空语言获取
        let result = hot_pool.acquire(&Language::Unknown).await;
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
        
        // 测试释放错误状态的沙箱
        let error_sandbox = create_test_sandbox(
            Language::Python, 
            SandboxState::Error("Test error".to_string())
        );
        
        let release_result = hot_pool.release(error_sandbox).await;
        // 错误状态的沙箱可能被接受但会在后续清理中被移除
        assert!(release_result.is_ok());
    }

    #[tokio::test]
    async fn test_hot_pool_stats_reset() {
        let config = Arc::new(create_test_pool_config());
        let hot_pool = HotPool::new(config);
        
        // 进行一些操作产生统计数据
        hot_pool.acquire(&Language::Python).await.unwrap(); // 失败的获取
        
        let sandbox = create_test_sandbox(Language::Python, SandboxState::Running);
        hot_pool.release(sandbox).await.unwrap();
        
        hot_pool.acquire(&Language::Python).await.unwrap(); // 成功的获取
        
        let stats_before_reset = hot_pool.get_stats().await.unwrap();
        assert!(stats_before_reset.successful_acquisitions > 0 || stats_before_reset.failed_acquisitions > 0);
        
        // 重置统计
        hot_pool.reset_stats().await;
        
        let stats_after_reset = hot_pool.get_stats().await.unwrap();
        assert_eq!(stats_after_reset.successful_acquisitions, 0);
        assert_eq!(stats_after_reset.failed_acquisitions, 0);
        assert_eq!(stats_after_reset.avg_response_time_ms, 0.0);
    }
}